<template>
	<div class="officeLocation" curPageName="officeManage123456789">

		<layoutContent>
			<template #right>
				<!-- 搜索模块儿 -->
			<div>

				<serachBar custom_class="myclass" placeholder="办公地" :close-advanced=true :search_val=search_val
					@searchEvent="searchFn">
					<template #header>
						<div>
							<el-select v-model="state.country" style="min-width: 240px;" @change="getLocationFun" clearable :placeholder="$t('staff_officeLocation.all_country')">
								<el-option v-for="oItem in officeLocationList" :key="oItem.value" :label="oItem.label"
									:value="oItem.value" />
							</el-select>
						</div>
					</template>

					<template #footer>

						<el-button v-auth="{'authArr':authArr,'key':'officeAdd'}" type="primary"
							@click="onPlus">{{$t("staff_officeLocation.add_office_btn")}}</el-button>
					</template>
				</serachBar>
			</div>
			<div class="merak-table-wrapper">
				<MerakXTable ref="tableRef" v-bind="tablePayload" :query-columns="handleQueryColumns"
					:query-data="handleQueryData">

					<template #handler="{ row }">
						<div style="display: flex;">
							<el-button v-auth="{'authArr':authArr,'key':'officeEdit'}" type="primary" link
								@click="saveEdit(row)"> {{$t("merak.edit")}}
							</el-button>
							<el-button v-auth="{'authArr':authArr,'key':'merge'}" type="primary" link @click="merge(row)">
								{{$t("merak.merge")}} </el-button>
							<el-button v-auth="{'authArr':authArr,'key':'delete'}"  :type="row.job_num?'':'danger'"  
							:disabled="row.job_num>0" link @click="delCompany(row)">
								{{$t("merak.delete")}} </el-button>
						</div>
					</template>

				</MerakXTable>
			</div>
			</template>
		</layoutContent>
	 

		<!-- 弹窗模块儿 -->
		<div class="drawer">

			<el-dialog modal-class="merak_modal" v-model="drawerOffice" direction="rtl" :close-on-click-modal="false"
				:close-on-press-escape="false" width="500">
				<template #header>
					<div class="merak_modal_title">{{companyTitle}}</div>
				</template>
				<div class="">
					<el-form :model="officeLocationForm" ref="officeLocationRef" :rules="officeLocationRules"
						label-position="top">

						<el-form-item :label="$t('staff_officeLocation.office_location_cn')" prop="office_location_cn">
							<el-input class="qf_input" v-model="officeLocationForm.office_location_cn" />
						</el-form-item>

						<el-form-item :label="$t('staff_officeLocation.office_location_ru')" prop="office_location_ru">
							<el-input class="qf_input" v-model="officeLocationForm.office_location_ru" />
						</el-form-item>

						<el-form-item :label="$t('staff_officeLocation.country')" prop="country">
							<el-radio-group v-model="officeLocationForm.country">
								<el-radio v-for="item in officeLocationList" :label="item.value"
									:value="item.value">{{item.label}}</el-radio>

							</el-radio-group>

						</el-form-item>
						<el-form-item :label="$t('staff_officeLocation.office_location_address')" prop="office_location_address">
							<el-input class="qf_textare" type="textarea" maxlength="300"
								:autosize="{  minRows: 3, maxRows: 10 }" show-word-limit
								v-model="officeLocationForm.office_location_address" />
						</el-form-item>




					</el-form>

				</div>

				<template #footer>
					<el-button type="default" @click="cancelEmpty(officeLocationRef)">{{$t("merak.cancel")}}</el-button>
					<el-button type="primary" plain v-if="editShow" :loading="loadingState"
						@click="saveContinue('2',officeLocationRef)">{{$t("merak.save_continue")}}</el-button>
					<el-button type="primary" @click="submitForm('1',officeLocationRef)"
						:loading="loadingState">{{$t("merak.save")}}</el-button>

				</template>
			</el-dialog>

			<!-- 合并 -->
			<el-dialog modal-class="" v-model="mergeStation" direction="rtl" :close-on-click-modal="false"
				:close-on-press-escape="false" width="450">
				<template #header>
					<div class="merak_modal_title">{{mergeTitle}}</div>
				</template>
				<div  >
					<el-form :model="mergeForm" ref="mergeRef" label-width="auto" :rules="mergeRules"
						label-position="top">
						<el-row :gutter="20">

							<el-col :span="24">
								<el-form-item :label="$t('staff_officeLocation.old_office_location')">
									<span class="label_show">{{mergeForm.old_office_title}}</span> 
								</el-form-item>
							</el-col>
						</el-row>
						<el-row :gutter="20">

							<el-col :span="24">
								<el-form-item :label="$t('staff_officeLocation.merge_to')"
									prop="new_office_location_id">
									<el-select class="qf_select" style="width: 100%;" filterable
										v-model="mergeForm.new_office_location_id">
										<el-option v-for="cItem in officeLocalList" :key="cItem.office_location_id" :label="cItem.office_location_cn"
											:value="cItem.office_location_id" />
									</el-select>

								</el-form-item>
							</el-col>
						</el-row>



					</el-form>

				</div>

				<template #footer>
					<el-button type="default" @click="merakCancel(mergeRef)">{{$t("merak.cancel")}}</el-button>
					<el-button type="primary" @click="merakConfirm(mergeRef)"
						:loading="loadingState">{{$t("merak.confirm")}}</el-button>

				</template>
			</el-dialog>

		</div>

	</div>


</template>

<script setup lang="ts" name="officeLocation">
	import layoutContent from "@/components/LayoutComponents/index.vue";
	import { Plus, Edit, Delete, EditPen } from '@element-plus/icons-vue';
	import { ref, reactive, computed, getCurrentInstance, nextTick } from "vue";
	import { getAlltree } from "@/minxins/useOrgsStore";//获取组织架构树
	import serachBar from "@/components/SearchBar/index";
	import MerakXTable, { MerakXTableInstance, MerakXTableColumn, MerakXTableQuery } from "@/components/MerakXTable";
	import { Path, getTableColumns, getTableData } from "@/api/modules/table";
	import useLoading from "@/hooks/useLoading";
	// 使用队列 loading 管理初始化页面加载状态
	const { queueLoading, queueId } = useLoading();

	import { moreConfirm, confirmWarningMsg, successMsg, warnMsg, failMsg, confirmSuccessMsg, delConfimMsg } from "@/utils/messageUtils";
	import { getOfficeLocationListApi, saveOfficeLocationApi, delOfficeLocationApi,getOfficeLocationAllApi,mergeOfficeApi } from "@/api/modules/personalManagementApi/officeLocation";




	const tableRef = ref < MerakXTableInstance > ();





	//#region 表单编辑

	const officeLocationRef = ref();
	const loadingState = ref(false);//loading状态值
	const { proxy } = getCurrentInstance();
	let companyTitle = ref(proxy.$t("staff_officeLocation.add_office_title"));
	let drawerOffice = ref(false);
	let editShow = ref(true);

	//默认表单
	const officeLocationList = reactive([
		{ label: proxy.$t("staff_officeLocation.china"), value: 1 },
		{ label: proxy.$t("staff_officeLocation.russia"), value: 2 },
		{ label:proxy.$t("staff_officeLocation.belarus"), value: 3 },
	])


	//表单参数结构
	const officeLocationForm = ref({
		office_location_id: '',//新增时不需要  
		office_location_cn: "",//中文名
		office_location_ru: "",//组织名称(俄文)
		country: 1,//所属国家
		office_location_address:'',//所属办公地
	});
	const officeLocationRules = reactive({
		office_location_cn: [{ required: true, message: proxy.$t("main.requiredMsg"), trigger: "blur" }],
		office_location_ru: [{ required: true, message: proxy.$t("main.requiredMsg"), trigger: "blur" }],
		office_location_address: [{ required: true, message: proxy.$t("main.requiredMsg"), trigger: "blur" }],
		country: [{ required: true, message: proxy.$t("main.requiredMsg"), trigger: "blur" }],
	});

	//保存并添加
	const saveContinue = (typebtn: string, formEl: FormInstance | undefined) => {

		submitForm(typebtn, formEl)
	}
	//保存

	const submitForm = async (typebtn: string, formEl: FormInstance | undefined) => {
		if (!formEl) return;
		await formEl.validate((valid, fields) => {
			if (valid) {
				//保存
				loadingState.value = true;
				saveOfficeLocationApi(officeLocationForm.value).then(res => {
					// console.log(res);
					loadingState.value = false;
					if (res.code == ResultEnum.SUCCESS) {
						getAlltree();//初始化组织架构
						successMsg(proxy.$t("merak.action_success"));
						if (typebtn == 1) {
							//关闭弹窗
							drawerOffice.value = false;

						}
						formEl.resetFields();
						tableRef.value?.reloadData();
						officeLocationForm.value = resetForm();
						return;
					}
					if (res.code == ResultEnum.ERROR) {
						failMsg(res.message)
					}
				})
			} else {
				// console.log(res);
				console.log("error submit!", fields);
			}
		});
	};


	//删除
	const delCompany = (rows) => {
		delConfimMsg({
			callback: val => {
				if (val == "confirm") {
					delOfficeLocationApi({ office_location_id: rows.office_location_id }).then(res => {
						if (res.code == ResultEnum.SUCCESS) {
							successMsg(proxy.$t("merak.delete_success"));
							tableRef.value?.reloadData();
						}
						if (res.code == ResultEnum.ERROR) {
							failMsg(res.message)
						}

					})
				}
			}
		});
	}

	//编辑
	const saveEdit = (rows) => {
		let { office_location_id, office_location_cn, office_location_ru, country,office_location_address } = JSON.parse(JSON.stringify(rows));;
		officeLocationForm.value = {
			office_location_id: office_location_id,//新增时不需要  
			office_location_cn: office_location_cn,//中文名
			office_location_ru: office_location_ru,//组织名称(俄文)
			country: country,//所属国家
			office_location_address:office_location_address
		};
		//打开弹窗
		drawerOffice.value = true;
		editShow.value = false;
		companyTitle.value = proxy.$t("staff_officeLocation.edit_office_title");
	}
	//取消
	const cancelEmpty = (formEl: FormInstance | undefined) => {
		if (!formEl) return;
		formEl.resetFields();
		drawerOffice.value = false;
	}
	//新增
	const onPlus = () => {
		drawerOffice.value = true;
		editShow.value = true;
		companyTitle.value = proxy.$t("staff_officeLocation.add_office_title");
		officeLocationForm.value = resetForm();
	}
	//重置表单
	const resetForm = () => {
		return {
			office_location_id: '',//新增时不需要  
			office_location_cn: "",//中文名
			office_location_ru: "",//组织名称(俄文)
			country: 1,//所属国家
		};
	}
	//#endregion

	//#region 合并
	const mergeRef = ref();
	const officeLocalList = ref();//当前部门下的所有岗位
	const mergeStation = ref(false);
	const mergeTitle = ref("合并办公地点");
	const mergeForm = ref({ new_office_location_id: '' })

	const mergeRules = reactive({
		new_office_location_id: [{ required: true, message: proxy.$t("main.requiredMsg"), trigger: "change" }]
	});


	//合并打开
	const merge = (row) => {
		console.log(row, "合并、。。。。")
		let { office_location_id, office_location_cn, office_location_ru ,country} = row;
		getOfficeAllList(office_location_id)
		let old_office_title = office_location_ru;
		if (proxy.$t("lang") == 'zh') {
			old_office_title = office_location_cn;
		}
		mergeStation.value = true;
		mergeForm.value = {
			old_office_location_id: office_location_id,
			country:country,
			new_office_location_id:'' ,
			old_office_title: old_office_title,

		}
		console.log(mergeForm.value)
	}

	//获取当前部门下的所有岗位
	const getOfficeAllList = (office_location_id) => {
		getOfficeLocationAllApi({curr_office_location_id:office_location_id}).then(res => {
			if (res.code == ResultEnum.SUCCESS) {
				let data = res.data; 
				officeLocalList.value = data[mergeForm.value.country]; 
			}
		})
	}
	//baocun 

	const merakConfirm = async (formEl: FormInstance | undefined) => {
		if (!formEl) return;
		await formEl.validate((valid, fields) => {
			if (valid) {
				//保存
				loadingState.value = true;
				mergeOfficeApi(mergeForm.value).then(res => {
					// console.log(res);
					loadingState.value = false;
					if (res.code == ResultEnum.SUCCESS) {
						getAlltree();//初始化组织架构
						successMsg(proxy.$t("merak.action_success"));
						mergeStation.value = false;


						tableRef.value?.reloadData();
						return;
					}
					if (res.code == ResultEnum.ERROR) {
						failMsg(res.message);;

					}
				}).catch(err => {
					loadingState.value = false;
				})
			} else {
				console.log("error submit!", fields);

			}
		});
	}
	//取消
	const merakCancel = (formEl: FormInstance | undefined) => {
		if (!formEl) return;
		formEl.resetFields();
		mergeStation.value = false;
	}
	//#endregion


	//#region 列表




	// 页面配置数据
	const state = reactive < {
		key_words: string,
		country: Number,
		columnType: Array
	} > ({
		key_words: '',
		country: '',
		columnType: []
	});

	// 动态计算表格的外部筛选数据
	const params = computed(() => ({ key_words: state.key_words, country: state.country }));
	const columnTypeNew = computed(() => (state.columnType))
	// 表格配置属性
	const tablePayload = reactive < MerakXTableProps > ({
		// 列设置存储的数据对照值
		columnsByStore: [],
		// 表格行数据的唯一 key, 跟后端同步
		rowKey: "org_id",
		// 初始化的外部筛选数据
		params,
		// 展示选中列及操作列, 可通过传入对象形式扩展特殊列的渲染插槽, 例如
		columnType: columnTypeNew,
		enabledExport:false,//导出
		// columnType: ['selection',"multiple", "handle"],
		// 批量操作选项
		batches: [{ type: "delete", text: "批量删除", color: "red" }],
		// 操作列选项
		// handles: [{ type: "delete", text: "删除", color: "red" }]
	});

	//获取数据

	// 权限数组
	const authArr = ref({});
	//查询
	let search_val = ref("");
	const searchFn = (e) => {
		state.key_words = e.search;
	}
	const getLocationFun = (e) => {
		console.log(e, "===")
		// state.country=e;
	}
	//列表内容展示区
	const handleQueryData: MerakXTableInstance["queryData"] = async ({ page, sorts, filters, from }) => {
		const params: Record<string, any> = {};
		if (!!page) {
			Object.assign(params, { ...page }, from);
		}
		return await getOfficeLocationListApi(params).then(res => {
			// console.log(res)
			let authList = res?.auth_list;
			if (authList) {

				authArr.value = authList;

				if (authList?.officeEdit.show || authList?.delete.show) {
					state.columnType = [{ type: 'handle', width: proxy.$t("lang") == 'zh' ? 150 : 250, slot: 'handler' }]
				}
				tablePayload.enabledExport = !!res?.auth_list?.export?.show;
			}

			if (res.code == ResultEnum.SUCCESS) {
				let data = res.data;
				const { table_data, language } = data as { table_data: Record<string, any>; language: Record<string, any> };

				return table_data;
			}
		})

	};


	// 获取表头数据
	const handleQueryColumns: MerakXTableInstance["queryColumns"] = async () => {
		// 初始化接口需要传入队列 loading 暴露的 id
		return getTableColumns(Path.officeLocation, queueId.value).then(({ code, data }) => {
			if (code == ResultEnum.SUCCESS) {
				// 克隆表头数据作为列设置的对照数据
				tablePayload.columnsByStore = JSON.parse(JSON.stringify(data.columns));
				return {
					...data
				};
			}
		});
	};
	//#endregion
</script>

<style scoped lang="scss">
	@import "./index.scss";
</style>